# Author: Sanmu
# CreatTime: 2024/10/18
# Descriptior：接口关键字驱动
import requests
from jsonpath import jsonpath
from conf.set_conf import read_conf


class ApiKeys:
    def __init__(self, env):
        self.env = env

    #get请求
    def do_get(self, path, params=None, headers=None, **kwargs):
        url = self.set_url(path)
        headers = self.set_headers(headers)
        return requests.get(url=url, params=params, headers=headers, **kwargs)

    #post请求
    def do_post(self, path, data=None, headers=None, **kwargs):
        url = self.set_url(path)
        headers = self.set_headers(headers)
        return requests.post(url=url, data=data, headers=headers, **kwargs)

    #获取响应文本
    def get_text(self, res, key):
        values = jsonpath(res,f'$..{key}')
        if values:
            if len(values) == 1:
                return values[0]
            else:
                return values
        else:
            return '找不到值'

    # 断言校验
    def assert_text(self, expected, res, key):
        try:
            reality = self.get_text(res, key)
            assert str(expected) == str(reality), f'''
                期望值：{expected},
                实际值：{reality},
                断言结果：{expected} != {reality},
                断言失败！
            '''
            return True
        except:
            return False

    def set_url(self, path):
        url = read_conf(self.env,'HOST')
        if path:
            url = url + path
        return url
    def set_headers(self, headers):
        base_headers = {
            'User-Agent':''
        }
        if read_conf('params','access-token'):
            token = read_conf('params','access-token')
            base_headers['access-tokeen'] = token
        if headers:
            base_headers.update(headers)
        return base_headers